package com.lxkpt.util;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

@Component
public class FtpUtil {

    //ftp服务器ip地址
    private static final String FTP_ADDRESS = "47.106.230.176";
    //端口号
    private static final int FTP_PORT = 21;
    //用户名
    private static final String FTP_USERNAME = "ftpuser";
    //密码
    private static final String FTP_PASSWORD = "ftp123456";
    //图片路径
    public final String FTP_BASEPATH = "/var/ftp/ftpuser/images";
    //图片访问路径
    public final String FTP_BASEPATH_SERVER = "http://www.lxkpt.com:81/images";

    /**
     * 上传文件
     *
     * @param datePath 时间
     * @param originFileName 文件名
     * @param input
     * @return
     */
    public boolean uploadFile(String datePath, String originFileName, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();
        ftp.setControlEncoding("GBK");
        try {
            int reply;
            ftp.connect(FTP_ADDRESS, FTP_PORT);
            ftp.enterLocalPassiveMode(); //被动模式
            ftp.login(FTP_USERNAME, FTP_PASSWORD);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (!ftp.changeWorkingDirectory(FTP_BASEPATH + datePath)) {
                String[] dirs = datePath.split("/");
                String tempPath = FTP_BASEPATH;
                for (String dir : dirs) {
                    if (null == dir || "".equals(dir)) continue;
                    tempPath += "/" + dir;
                    if (!ftp.changeWorkingDirectory(tempPath)) {
                        if (!ftp.makeDirectory(tempPath)) {
                            ftp.changeWorkingDirectory(tempPath);
                        }
                    }
                }
            }

            ftp.storeFile(originFileName, input);
            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
}
